iT邦幫忙

0

[JavaScript學習筆記] - 常見的「發網路請求」寫法

  • 分享至 

  • xImage
  •  

1. fetch + then(最基本)
瀏覽器內建,不用裝套件,但一層一層 .then 串接

fetch("https://api.example.com/data")
  .then(function (response) {
    return response.json();
  })
  .then(function (data) {
    console.log(data);
  });

2.fetch + async/await(現在最常用)
寫起來像同步程式碼,比較好讀

async function getData() {
  const response = await fetch("https://api.example.com/data");
  const data = await response.json();
  console.log(data);
}

3. XMLHttpRequest(老派寫法)
fetch 出現前的標準寫法,現在比較少人用,但舊專案還看得到

const xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/data");
xhr.onload = function () {
  console.log(xhr.responseText);
};
xhr.send();

4. axios(第三方套件)
需要 npm install axios,比 fetch 多一些方便功能(例如自動轉 JSON、錯誤處理較簡單)

axios.get("https://api.example.com/data")
  .then(function (res) {
    console.log(res.data);
  });

實際操作練習:

網路請求練習檔-連結提供:

https://drive.google.com/file/d/1LC8Yqx5dI1jMGakVPEZGPNsED0VrjMqg/view?usp=drive_link

  • 下載後打開先按 F12 開啟 DevTools,再切到 Network 分頁
  • 每按一個按鈕,觀察 Network 分頁多出來的請求
  • 再切到 Console 分頁,看看有沒有錯誤訊息

四個都能正常運作後,可以試著把 API 網址改成不存在的路徑(例如把 /posts/1 改成 /posts/9999),看看每種寫法在請求失敗時的反應有什麼不同——這是很好的除錯練習。

下載後直接用瀏覽器打開就能操作。四個按鈕分別對應四種寫法,都是打同一支測試 API(JSONPlaceholder),方便比較。


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言